import { defineStore } from 'pinia'
import { ref } from 'vue'
import { cartApi } from '@/api/CartApi.js'
import { useUserStore } from './userStore.js'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {
  const items = ref([]) // 购物车项数组
  const lastUpdated = ref(null) // 最后更新时间
  const isLoading = ref(false) // 加载状态
  const error = ref(null) // 错误信息

  // 获取用户store
  const userStore = useUserStore()

  /**
   * 初始化购物车（登录成功后调用）
   */
  const initCart = async () => {
    if (!userStore.isLogin) {
      console.log('用户未登录，跳过购物车初始化')
      return
    }

    isLoading.value = true
    error.value = null
    try {
      const response = await cartApi.getCartByUserId(userStore.userAccount.userId)

      if (response.code === 1) {
        items.value = response.data || []
        lastUpdated.value = new Date()
      } else {
        console.warn('购物车数据格式不符:', response)
      }
    } catch (err) {
      error.value = err.message || '获取购物车失败'
      console.error('初始化购物车失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
 * 添加商品到购物车
 * @param {Object} product 商品信息
 * @param {number} [quantity=1] 数量，默认为1
 * @returns {Promise<CartDTO>} 返回包含商品信息的购物车DTO
 */
const addToCart = async (product, quantity = 1) => {
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录')
    throw new Error('请先登录')
  }

  isLoading.value = true
  error.value = null

  try {
    // 1. 准备请求数据
    const cartDTO = {
      userId: userStore.userAccount.userId,
      productId: product.productId,
      quantity: quantity
    }

    // 2. 调用API添加到服务器
    const response = await cartApi.addToCart(cartDTO)

    // 3. 处理响应
    if (response.code === 1) {
      const addedCart = response.data

      // 4. 更新本地状态
      const existingIndex = items.value.findIndex(
        item => item.productId === product.productId
      )

      if (existingIndex !== -1) {
        // 如果已存在则更新
        items.value[existingIndex] = addedCart
      } else {
        // 否则新增
        items.value.push(addedCart)
      }

      ElMessage.success('添加购物车成功')
      return addedCart
    } else {
      throw new Error(response.message || '添加购物车失败')
    }
  } catch (err) {
    error.value = err.message || '添加购物车失败'
    console.error('添加购物车失败:', {
      error: err,
      product,
      quantity
    })
    ElMessage.error(error.value)
    throw err
  } finally {
    isLoading.value = false
  }
}

  /**
 * 更新购物车商品数量
 * @param {string} cartId 购物车项ID
 * @param {number} quantity 新数量
 */
const updateCartQuantity = async (cartId, quantity, isDelta = true) => {
  isLoading.value = true;
  error.value = null;

  try {
    const response = await cartApi.updateCartQuantity(cartId, quantity, isDelta);

    if (response.code === 1) {
      // 更新本地状态
      const index = items.value.findIndex(item => item.cartId === cartId);
      if (index !== -1) {
        if (response.isDeleted) {
          items.value.splice(index, 1); // 删除商品
        } else if (isDelta) {
          items.value[index].quantity += quantity; // 增量更新
        } else {
          items.value[index].quantity = quantity; // 绝对数量更新
        }
        lastUpdated.value = new Date();
      }
      return response.data;
    } else {
      throw new Error(response.msg || '更新购物车数量失败');
    }
  } catch (err) {
    error.value = err.message || '更新数量失败';
    console.error('更新购物车数量失败:', {
      error: err,
      cartId,
      quantity,
      isDelta
    });
    throw err;
  } finally {
    isLoading.value = false;
  }
}

  /**
   * 从购物车移除商品
   * @param {string} cartId 购物车项ID
   */
  const removeFromCart = async (cartId) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await cartApi.removeFromCart(cartId)

      if (response.code === 1) {
        // 从本地状态移除
        items.value = items.value.filter(item => item.cartId !== cartId)
      }
    } catch (err) {
      error.value = err.message || '移除商品失败'
      console.error('移除购物车商品失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 清空购物车（退出登录时调用）
   */
  const clearCart = () => {
    items.value = []
    lastUpdated.value = null
    error.value = null
  }

  /**
   * 根据索引获取购物车项
   * @param {number} index 索引
   * @returns {Object|null} 购物车项
   */
  const getCartItem = (index) => {
    return items.value[index]
  }

  // 在cartStore中添加
const removeMultipleFromCart = async (cartIds) => {
    for (const cartId of cartIds) {
        await removeFromCart(cartId);
    }
};

  // 计算属性
  const totalItems = () => items.value.reduce((total, item) => total + item.quantity, 0)

  const totalAmount = () => items.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)

  const getItemByProductId = (productId) => {
    return items.value.find(item => item.productId === productId)
  }

  return {
    items,
    lastUpdated,
    isLoading,
    error,
    totalItems,
    totalAmount,
    getItemByProductId,
    initCart,
    addToCart,
    updateCartQuantity,
    removeFromCart,
    clearCart,
    getCartItem,
    removeMultipleFromCart
  }
})